package com.zj.study.test;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;

@Slf4j
public class EasyExcelSetting {


  /**
   * 设置响应头
   *
   * @param response 回应的请求数据
   * @param fileName 文件名字
   */
  public static void setHead(HttpServletResponse response, String fileName) {

    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("utf-8");
    // 这里URLEncoder.encode可以防止中文乱码
    fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
    response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

  }

  /**
   * 设置Excel的格式
   *
   * @return 格式化后的Excel
   */
  public static HorizontalCellStyleStrategy formatExcel() {
    WriteCellStyle headWriteCellStyle = new WriteCellStyle();
    headWriteCellStyle.setFillBackgroundColor(IndexedColors.WHITE.getIndex());
    WriteFont headWriteFont = new WriteFont();
    headWriteFont.setFontHeightInPoints((short) 9);
    headWriteCellStyle.setWriteFont(headWriteFont);
    headWriteFont.setFontName("宋体");
    //headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
    // 内容的策略
    WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
    WriteFont contentWriteFont = new WriteFont();
    // 字体大小
    contentWriteFont.setFontHeightInPoints((short) 9);
    contentWriteCellStyle.setWriteFont(contentWriteFont);
    contentWriteFont.setFontName("宋体");
    // 设置自动换行
    contentWriteCellStyle.setWrapped(true);
    // 设置垂直居中
    contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    // 设置水平居中
    contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

    return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

  }

  /**
   * 设置头部单元格宽度
   */
  public static class ExcelWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> list,
        Cell cell, Head head, Integer integer, Boolean aBoolean) {
      // 设置宽度
      Sheet sheet = writeSheetHolder.getSheet();
      sheet.setColumnWidth(cell.getColumnIndex(), 4000);
    }
  }


}
